/*
 * 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, Card, Checkbox, Radio, Badge, Fragment, Pagination, Popconfirm, Switch } from 'antd';
import { $http } from '../../containers/config/https';
import store from '../../store';
import './style/index.less';
import PrescriptionRulesModal from './component/PrescriptionRulesModal';
import PrescriptRulesTabs from './component/PrescriptRulesTabs';
import CommonPagination from 'components/pagination/index';
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 SubCategoriesOfMedicalAdvice = Form.create()(
    class SubCategoriesOfMedicalAdvice extends React.Component {
        cacheOriginData = {};
        constructor() {
            super()
            this.state = {
                leftData: [],
                total: 0,
                page: 1,
                pageSize: 10,
                search: "",
                size: "small",
                checked: true
            }
        }
        componentDidMount = () => {
            // 初始化设置table的高度以及表体的高度
            if (document.querySelector('.ant-table-body')) {
                var x = document.querySelectorAll(".ant-table-body");
                for (var i = 0; i < x.length; i++) {
                    x[0].style.height = store.getState().tableHeight.y + 60 + 'px';
                    x[i].style.height = store.getState().tableHeight.y - 50 + 'px';
                    x[i].style.overflow = "auto";
                }
            }
            this.getMainTableColumns()
            this.handleFind()
        }
        //动态表头
        onColumnRef = (ref) => {
            this.columnRef = ref;
        }
        //关联处方类型操作弹窗
        onRef = (ref) => {
            this.modalRef = (ref)
        }
        //关联tabs
        onTabChild = (ref) => {
            this.tabChild = (ref)
        }
        //添加、编辑 处方类型
        openModal = (mes, row) => {
            this.modalRef.showModal(mes, row)
        }
        //删除 处方类型
        handleDelete = (e, row) => {
            let data = {
                params: [{
                    userID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : "",
                    ID: row.ID,
                }]
            }
            $http.post('urlS', this, {
                code: '03050153',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        message.success("删除成功")
                        this.handleFind()
                    }
                }
            })
        }
        //仅生效
        changeChecked = (e) => {
            this.setState({
                checked: e.target.checked
            }, () => {
                this.handleFind()
            })
        }
        // 获取主列表columns
        getMainTableColumns = () => {
            let data = {
                params: [{
                    compontName: "PrescType", // 处方类型
                    reactCode: ['PrescType'],
                    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>
                                        <span style={{ cursor: "pointer", color: '#1890ff' }} onClick={() => this.openModal("1", row)}>编辑</span>
                                        <Divider type="vertical" />
                                        <span>
                                            <Popconfirm title="删除不可恢复，你确定要删除吗?" onCancel={this.handlePopconfirm} onConfirm={(e) => this.handleDelete(e, row)} >
                                                <span className='span' style={{ cursor: "pointer", color: 'rgba(240,65,52,1)' }}>删除</span>
                                            </Popconfirm>
                                        </span>
                                    </span>

                                )
                            },
                        }
                        filterArr.push(seqArr)
                        this.setState({ leftDetailColumns: filterArr, widthTotal: res.totalWidth })
                        // console.log("res.totalWidth",res.totalWidth)
                    }
                }
            })
        }
        //查询处方规则--回车
        handleFindSub = () => {
            this.setState({
                page: 1,
                pageSize: this.state.pageSize,
                search: "search"
            }, () => {
                this.handleFind()
            })
        }
        //查询处方规则
        handleFind = (mes) => {
            const { pageSize, page, checked } = this.state
            let data = {}
            data = {
                params: [{
                    desc: this.props.form.getFieldValue("info"),
                    status: checked == true ? "Y" : "N",
                }],
                pagination: [{
                    pageSize: parseInt(pageSize),
                    currentPage: parseInt(page),
                }]
            }
            $http.post('urlS', this, {
                code: '03050154',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({
                            leftData: res.result.data,
                            total: res.result.totalCount,
                        })
                        if (!mes) {
                            this.tabChild.initTabs()
                        }
                    }
                }
            })
        }
        getLast = () => {
            //定位到最后一条
            let lastPage = Math.ceil((this.state.total + 1) / this.state.pageSize)
            this.setState({
                page: lastPage,
            }, () => {
                this.handleFind()
            })
        }
        // 显示分页总条数
        showTotal(total) {
            return `共 ${total} 条`;
        }
        // 修改page和pageSize 跳转至---
        onChange = (e) => {
            this.setState({ page: e, pageSize: this.state.pageSize }, () => {
                // 重新调用查询方法
                this.handleFind("1")
            })
        }
        // 页码改变的回调，参数是改变后的页码及每页条数
        PageChange = (page, pageSize) => {
            this.setState({ page: page, pageSize: pageSize }, () => {
                // 重新调用查询方法
                this.handleFind("1")
            });
        }
        //下拉选择页数
        onShowSizeChange = (page, pageSize) => {
            this.setState({ page: 1, pageSize: pageSize }, () => {
                // 重新调用查询方法
                this.handleFind("1")
            })
        }
        //根据医嘱子类ID获取医嘱子类接收科室
        getBigLocData = (prescriptID) => {
            const { pageRight, pageSizeRight } = this.state
            let data = {}
            data = {
                params: [{
                    prescriptID: prescriptID,
                    status: this.state.checkedRight == true ? "Y" : "N"
                }],
                pagination: [{
                    pageSize: pageSizeRight,
                    currentPage: pageRight,
                }]
            }
            $http.post('urlS', this, {
                code: '05100202',
                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)
                    }
                }
            })
        }
        //点击Row 左侧表格
        onClickRow = (record) => {
            return {
                onClick: () => {
                    this.setState({
                        prescriptID: record.ID,
                        rowIds: "",
                    })
                    // this.childBase.initData(record)
                    if (record.ID) {
                        if (this.state.rowId === "") {
                            this.setState({
                                rowId: record.ID,
                            });
                            // this.childBase.setDefalut(record)
                            this.getTbsGetRec(record.ID)
                            this.tabChild.canSave(record.ID)
                        } else {
                            if (this.state.rowId !== record.ID) {
                                this.setState({
                                    rowId: record.ID,
                                });
                                // this.childBase.setDefalut(record)
                                this.getTbsGetRec(record.ID)
                                this.tabChild.canSave(record.ID)
                                // this.tabChild.restFile()
                            } else {
                                this.setState({
                                    rowId: "",
                                    prescriptID: ""
                                });
                                // this.childBase.initDefalut(record)
                                this.tabChild.initTabs()
                                // this.childBase.initOrig()
                            }
                        }
                    }
                },
                onDoubleClick: () => {
                    this.setState({
                        rowId: "",
                        prescriptID: ""
                    });
                    // this.childBase.initDefalut(record)
                    // this.tabChild.initTabs()
                    // this.childBase.initOrig()
                }
            };
        }
        //返回添加状态
        initOrigin = () => {
            this.setState({
                rowId: "",
                rowIds: "",
                prescriptID: "",
                isDefalult: false,
                centerInfo: {},
                rightData: [],
            })
            this.tabChild.initTabs()
            this.props.form.resetFields()
        }
        //设置点击row颜色 --左侧表格
        setRowClassName = (record) => {
            return record.ID === this.state.rowId ? 'clickRowStyle' : '';
        }

        //点击是否设置为默认
        handleSwithChange = (v) => {
            this.setState({
                isDefalult: v
            })
        }
        canSave = () => {
            this.setState({
                canSave: false
            })
        }



        getTable = () => {
            //刷新左侧列表
        }
        //点击左侧 获取右侧tab数据
        getTbsGetRec = (SubID) => {
            this.tabChild.getRec(SubID)
            this.tabChild.getSubHopDa(SubID)
            this.tabChild.getSubUsageData(SubID)
        }

        render() {

            const { getFieldDecorator } = this.props.form;
            let { leftDetailColumns, } = this.state
            //开单类型
            let openLocOp = []
            this.state.publicLocArr && this.state.publicLocArr.map(item => {
                openLocOp.push(<Option key={item.id} role={item.descripts + '^' + item.descriptsSPCode} title={item.descripts} value={String(item.id)}>{item.descripts}</Option>)
            })
            //接收类型
            let getLocOp = []
            this.state.publicLocArr && this.state.publicLocArr.map(item => {
                getLocOp.push(<Option key={item.id} role={item.descripts + '^' + item.descriptsSPCode} title={item.descripts} value={String(item.id)}>{item.descripts}</Option>)
            })
            return (
                <div>
                    <Row gutter={60} className="majorCategoriesDom" style={{ marginRight: "0" }}>
                        <Col span={12} style={{ paddingRight: "0" }}>
                            <Card title="处方类型列表" bordered={false} style={{ marginRight: "4px", }} className="titleDom">
                                <Row>
                                    <Col span={16} style={{ marginRight: '10px' }}>
                                        <FormItem>
                                            {getFieldDecorator('info', {
                                                initialValue: undefined,
                                            })(
                                                <Input placeholder='输入描述回车查询,支持模糊搜索' onPressEnter={this.handleFindSub} autoFocus />
                                            )}
                                        </FormItem>
                                    </Col>
                                    <Col span={2}>
                                        <FormItem >
                                            {getFieldDecorator('checkInp', {
                                                initialValue: undefined,
                                                rules: [{ required: false, message: '' }],
                                            })(
                                                <Button style={{ background: 'rgba(66,185,131,1)', color: '#fff', }} onClick={this.openModal}>+处方类型</Button>
                                            )}
                                        </FormItem>
                                    </Col>
                                </Row>
                                <Row>
                                    <Checkbox checked={this.state.checked} onChange={this.changeChecked}>仅显示生效</Checkbox>
                                </Row>
                                <Table
                                    className="components-table-demo-nested"
                                    columns={leftDetailColumns}
                                    pagination={false}
                                    rowClassName={this.setRowClassName}
                                    onRow={this.onClickRow}
                                    rowKey={record => record.key}
                                    dataSource={this.state.leftData}
                                    bordered={true}
                                    style={{
                                        height: store.getState().tableHeight.y + 60 + 'px'
                                    }}
                                />
                                <CommonPagination size={this.state.size} page={this.state.page} current={this.state.page} total={this.state.total} search={this.state.search}
                                    onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={this.state.leftData}
                                    onChange={this.PageChange.bind(this)} />
                                {/* {
                                    this.state.leftData && this.state.leftData.length > 0 ? <Pagination
                                        size="small"
                                        showQuickJumper
                                        showSizeChanger
                                        defaultCurrent={1}
                                        current={this.state.page}
                                        total={this.state.total}
                                        onChange={this.PageChange}
                                        onRow={this.selectID}
                                        onShowSizeChange={this.onShowSizeChange}
                                        style={{ textAlign: "right", marginTop: '10px' }}
                                        showTotal={() => this.showTotal(this.state.total)}
                                    /> : ""
                                } */}

                            </Card>
                        </Col>
                        <Col span={12} style={{ paddingLeft: "6px", paddingRight: "0" }}>
                            <Card bordered={false} title="处方规则列表" className="moreInfoCard titleDom" style={{ paddingRight: "0" }}>
                                <PrescriptRulesTabs sendSubId={this.state.rowId} onTabChild={this.onTabChild}></PrescriptRulesTabs>
                            </Card>
                        </Col>
                    </Row>
                    <PrescriptionRulesModal getLast={this.getLast} handleFind={this.handleFind} onRef={this.onRef}></PrescriptionRulesModal>
                    <ColumnAuthoritysModel
                        clientWidth='800px'
                        compontName='PrescType'
                        configType="C"
                        onRef={this.onColumnRef}
                        reloadData={this.getMainTableColumns}
                    />
                </div>
            )
        }
    })
export default SubCategoriesOfMedicalAdvice