/*
 * Creator:     ML
 * CreatDate:   2019-10-09
 * 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 './css/index.less';
import DepAssDetailed from "./component/DepAssDetailed";
import DepAssFind from "./component/DepAssFind";
import DepAssModal from "./component/DepAssModal"
import CommonPagination from 'components/pagination/index';


const userData = sessionStorage.userData ? JSON.parse(sessionStorage.userData) : {}
const FormItem = Form.Item;
const Option = Select.Option;
const ConfigDepartmentalAssess = Form.create()(
    class ConfigDepartmentalAssess 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: [],//医嘱明细选中
                tempChildDis: false,//左侧编辑 选择类型
                btnStatus: true,
                selectedRow_right: [],
                selectrow: "",//获取行 当前选中行
                deteleOrdId: "",//选中删除行
                leftDisRow: false,
                ordTempId: 1,//挂号评估单科室选择值
                isAdd: false,//是否点击添加
                ordDetailValue: "",//医嘱明细输入值
                ordDetailData: [],//医嘱项表格数据
                OrdDaShow: false,//医嘱项表格数据显隐
                OrdDaRowId: "",//医嘱项表格行id
                OrdCanType: "",//医嘱项允许录入类型
                ordTemPrice: 0,//医嘱项行单价
                editDis: true,//未选中

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

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


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


                // 左侧表格
                checked: true,//默认选择生效
                total: 0,//医嘱项表格总数据
                page: 1,//页数
                pageSize: 10,//显示数
                //右侧表格
                totalRight: 0,
                pageRight: 1,
                pageSizeRight: 10,
                checkedRight: true,
                baseTempType: [],//添加门诊挂号评估单配置类型选择
                topInfo: {},
                centerInfo: {},
                isDefalult:false,
                canSave:true,
                size:"small",
                search:""
            }
            this.detailDeInput = React.createRef();
        }
        componentDidMount = () => {
            // 初始化设置table的高度以及表体的高度
            if (document.querySelector('.ant-table-body')) {
                document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y-36 + 'px'
            }
            // this.handleQuery()
            this.findChild.handleSearch();
            // this.getLocTypeSelect()
        }
        //子组件 查询
        OnChild=(ref)=>{
            this.findChild = ref
        }
        //子组件 新增
        onRef=(ref)=>{
            this.addChild = ref
        }
        //新增评估单
        addOutReg=()=>{
            this.addChild.showModal()
        }
        //编辑评估单
        handleEdit=(row)=>{
            this.addChild.showModal(row)
        }
        //子组件 弹框 科室下拉框
        sendLoc=(locArr)=>{
            this.addChild.getLocArr(locArr)
        }
        //子组件 明细 子段下拉框
        sendFile=(fileArr)=>{
            // console.log("fileArr",fileArr)
            this.detailChild.getFileArr(fileArr)
        }
        //子组件 明细
        onDetail=(ref)=>{
            this.detailChild = ref
        }
    //添加成功之后跳到最后一条
        getLast=(status,id)=>{
            // debugger
            //定位到最后一条
            if(id){
                // console.log("total",this.state.total,"pageSize",this.state.pageSize)
                let lastPage = Math.ceil((this.state.total + 1) / this.state.pageSize)
                // debugger
                this.setState({
                    page:lastPage,
                    rowId:id,
                })
               this.handleQuery(status)
                return
            }
        }
        //回车查找门诊挂号评估单配置数据
        handleQuery = (status,values) => {
            const { page, pageSize } = this.state
            let data = {}
            let checkFlag = "Y"
                if (status == true) {
                    checkFlag = "Y"
                }else if(status == false){
                    checkFlag = " "
                    this.findChild.initCheck()
                } else {
                    checkFlag = "Y"
                }
            data = {
                params: [{
                    userID:sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : "",
                    hospID:sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : "",
                    groupID:sessionStorage.userData ? JSON.parse(sessionStorage.userData).groupID : "",
                    locID:values&&values.locID?values.locID:"",
                    searchCode:values&&values.searchCode?values.searchCode:"",
                    active: checkFlag,
                }],
                pagination: [{
                    pageSize: parseInt(pageSize),
                    currentPage:parseInt(page),
                }]
            }
            $http.post('urlS', this, {
                code: '03040023',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0 && res.result.data) {
                         res.result.data && res.result.data.map((item, index) => {
                            res.result.data[index].key = Number(index)
                        })
                        this.setState({
                            rowId:"",
                            leftData: res.result.data,
                            total: res.result.totalCount
                        })
                    }
                    // if(res.result.data&&res.result.data.length==0&&res.result.totalCount>0){
                    //     let prevPage = this.state.page - 1
                    //     this.onChange(prevPage, this.state.pageSize)
                    //   }
                }
            })
        }
        // 显示分页总条数
        showTotal(total) {
            return `共 ${total} 条`;
        }
        // 页码改变的回调，参数是改变后的页码及每页条数
        PageChange = (e) => {
            this.setState({ page: e, pageSize: this.state.pageSize }, () => {
                // 重新调用查询方法
                this.findChild.handleSearch();
            });
        }
        //下拉选择页数
        onShowSizeChange = (page, pageSize) => {
            this.setState({ page: 1, pageSize: pageSize }, () => {
                // 重新调用查询方法
                this.findChild.handleSearch();
                this.setState({
                    search:"search"
                })
            })
        }
        // 调用子组件的连接事件 -- 右上基本信息
        OnChildrefs = (ref) => {
            this.child = ref
        }

        //点击Row 左侧表格
        onClickRow = (record) => {
            return {
                onClick: () => {
                    this.setState({
                        id: record.id,
                        centerInfo: {},
                        rowIds: "",
                        isDefalult: false
                    })
                    this.detailChild.initPagination()
                    if (record.id) {
                        if (this.state.rowId === "") {
                            this.setState({
                                rowId: record.id,
                                topInfo: record
                            });
                            this.detailChild.getDetail(record.id,record)
                            // this.detailChild.getSize()
                        } else {
                            if (this.state.rowId !== record.id) {
                                this.setState({
                                    rowId: record.id,
                                    topInfo: record
                                });
                                this.detailChild.getDetail(record.id,record)
                                // this.detailChild.getSize()
                            } else {
                                this.setState({
                                    rowId: "",
                                    topInfo: {},
                                    id: ""
                                    //   ordShow:false
                                });
                                this.props.form.resetFields();
                                this.detailChild.initHBRVLSid();
                                // this.detailChild.getSize();
                            }
                        }
                    }
                },
                onDoubleClick: () => {
                    this.setState({
                        rowId: record.id,
                    })
                    this.detailChild.getDetail(record.id,record)
                    // this.getBigLocData(record.id)
                }
            };
        }
        sarchInit=()=>{
            this.detailChild.initHBRVLSid()
            this.initOrigin()
        }
        //返回添加状态
        initOrigin = () => {
            this.setState({
                rowId: "",
                rowIds:"",
                isDefalult:false,
                centerInfo:{},
                rightData:[]
            })
            this.props.form.resetFields()
        }
        //设置点击row颜色 --左侧表格
        setRowClassName = (record) => {
            return record.id === this.state.rowId ? 'clickRowStyle' : '';
        }

        //点击是否设置为默认
        handleSwithChange = (v) => {
            this.setState({
                isDefalult: v
            })
        }
        //是否默认
        onChangeSwith = (v, record) => {
            let data = {}
            data = {
                params: [{
                    updateUserID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : "",
                    defaultFlag: v == true ? "Y" : "N",
                    orderCatRecLocID: record.orderCatRecLocID,
                }],
            }
            $http.post('urlS', this, {
                code: '05100203',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        message.success("设置成功")
                        this.setState({
                            isDefalult: v,
                            centerInfo:record,
                            rowIds:record.orderCatRecLocID,
                        })
                        this.getBigLocData(this.state.id)
                    }
                }
            })
        }
        //点击右侧表格行
        onClickRightRow = (record) => {
            const { rightData } = this.state
            return {
                onClick: () => {
                    this.setState({
                        centerInfo: {},
                        isDefalult: false,
                    })
                    this.props.form.resetFields();
                    if (record.orderCatRecLocID) {
                        if (this.state.rowIds === "") {
                            this.setState({
                                rowIds: record.orderCatRecLocID,
                                centerInfo: record,
                                isDefalult: record.defaultFlag == "Y" ? true : false
                            });
                            //   this.getBigLocData(record.id)
                        } else {
                            if (this.state.rowIds !== record.orderCatRecLocID) {
                                this.setState({
                                    rowIds: record.orderCatRecLocID,
                                    centerInfo: record,
                                    isDefalult: record.defaultFlag == "Y" ? true : false
                                });
                                // this.getBigLocData(record.id)
                            } else {
                                this.setState({
                                    rowIds: "",
                                    centerInfo: {},
                                    isDefalult: false
                                    //   ordShow:false
                                });
                                this.propsfrom.resetFields()
                                // this.props.form.resetFields();
                            }
                        }
                    }
                },
            }
        }
        //点击右侧医院选项过滤开单科室
        handleHosp=(e,id)=>{
            this.props.form.setFieldsValue({getOpenLoc:undefined ,getLoc:undefined})
        }
        setRowClassNames = (record) => {
            return record.orderCatRecLocID === this.state.rowIds ? 'clickRowStyle' : '';

        }
        handleLeftOk = () => {
            this.props.form.validateFields((err, values) => {

            })
        }
        handleRightCancel=()=>{
            this.setState({
                centerInfo:{}
            })
            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 : "",
                            defaultFlag: this.state.isDefalult == true ? "Y" : "N",
                            orderCatRecLocID: this.state.rowIds,
                            id: this.state.id,
                            hospitalID: values.getHop,
                            locTypeID: values.getLocType,
                            locID: values.getOpenLoc,
                            recLocID: values.getLoc,
                            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 : "",
                            defaultFlag: this.state.isDefalult == true ? "Y" : "N",
                            id: this.state.rowId,
                            orderCatRecLocID: this.state.rowIds || "",
                            hospitalID: values.getHop,
                            locTypeID: values.getLocType,
                            locID: values.getOpenLoc,
                            recLocID: values.getLoc,
                            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: '05100203',
                        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.getBigLocData(this.state.id)
                                            return
                                        }
                                    }
                                    this.setState({
                                        checkedRight:true
                                    })
                                     this.getBigLocData(this.state.id)
                                }else{
                                    message.success("添加成功")
                                    this.props.form.resetFields()
                                    this.setState({
                                        isDefalult:false
                                    })
                                    if ((values.getDateFrom && values.getDateFrom) && (values.getDateTo && values.getDateTo)) {
                                        if (moment(values.getDateTo).format('YYYYMMDD') < moment().format('YYYYMMDD')) {
                                            this.setState({
                                                checkedRight:false
                                            })
                                            this.getBigLocData(this.state.id)
                                            return
                                        }
                                    }
                                    this.setState({
                                        checkedRight:true
                                    })
                                    this.getBigLocData(this.state.rowId)
                                }
                            }
                        }
                    })
                }
            })
        }
        canSave=()=>{
            this.setState({
                canSave:false
            })
        }
        handleTemDaCancel = () => {
            this.setState({
                OrdDaShow: false
            })
        }
        //删除挂号评估单科室
        handleDelete=(e,record)=>{
            let data = {}
            let idArr = []
            idArr.push(String(record.id))
            data = {
                params: [{
                    userID:sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : "",
                    hospID:sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : "",
                    groupID:sessionStorage.userData ? JSON.parse(sessionStorage.userData).groupID : "",
                    id:idArr,
                }],
            }
            $http.post('urlS', this, {
                code: '03040022',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        message.success("删除成功")
                       this.handleQuery();
                    }
                }
            })
        }
        //删除挂号评估单科室
        delate=(e,record)=>{
            let data = {}
            data = {
                params: [{
                    updateUserID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : "",
                    orderCatRecLocID:record.orderCatRecLocID,
                }],
            }
            $http.post('urlS', this, {
                code: '05100204',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        message.success("删除成功")
                        this.getBigLocData(this.state.rowId)
                    }
                }
            })
        }
        //初始化信息
        initData = () => {
            this.setState({
                isMod: -1,
                ordShow: false,
                tempChildDis: false
            })
            this.props.form.setFieldsValue({ docMesName: undefined });
            this.props.form.setFieldsValue({ othName: undefined });
            this.props.form.setFieldsValue({ docMesType: undefined });
        }
        //点击添加/修改门诊挂号评估单配置弹窗取消按钮
        handleCancel = () => {
            this.setState({
                visible: false
            })
            this.initData()
        }

        render() {
            //左侧查询数据表
            const leftDetailColumns = [
                {
                    align: "center",
                    title: '医院名称',
                    dataIndex: 'hospDesc',
                    key: '2',
                    render:(value, row, index)=>{
                          return <Tooltip placement="top" title={value}>{value}</Tooltip>
                      },
                      onCell:()=>{
                        return {
                          style: {
                              maxWidth: 100,
                              overflow: 'hidden',
                              whiteSpace: 'nowrap',
                              textOverflow: 'ellipsis',
                              cursor: 'pointer'
                          }
                      }
                      }
                }, {
                    align: "center",
                    title: '科室名称',
                    dataIndex: 'locDesc',
                    key: '3',
                }, {
                    align: "center",
                    title: '评估单描述',
                    dataIndex: 'descripts',
                    key: '4',
                    render:(value, row, index)=>{
                        return <Tooltip placement="top" title={value}>{value}</Tooltip>
                    },
                    onCell:()=>{
                      return {
                        style: {
                            maxWidth: 100,
                            overflow: 'hidden',
                            whiteSpace: 'nowrap',
                            textOverflow: 'ellipsis',
                            cursor: 'pointer'
                        }
                    }
                    }
                }, {
                    align: "center",
                    title: '状态',
                    dataIndex: 'status',
                    key: '5',
                    render: (value, row, index) => {
                        if(value=="Y"){
                            return "生效"
                        }else if(value=="N"){
                            return "失效"
                        }
                        else{
                            return value
                        }

                    },
                },
                {
                    align: "center",
                    title: '操作',
                    dataIndex: 'createdAt',
                    key: '6',
                    render: (value, row, index) => {
                        return (
                            <span>
                                 <span  className='span' style={{cursor:"pointer"}} onClick={()=>this.handleEdit(row)}>编辑</span>
                                {/* 分割线 */}
                                <Divider type="vertical" />
                                <Popconfirm title="删除不可恢复，你确定要删除吗?" onCancel={this.handlePopconfirm} onConfirm={(e) => this.handleDelete(e, row)} >
                                    <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.hospID} onClick={(e,)=>this.handleHosp(e,item.hospID)} value={String(item.hospID)}>{item.hospDesc}</Option>)
            })
            //科室类型
            let locOp = []
            this.state.locArr && this.state.locArr.map(item => {
                locOp.push(<Option key={item.id} role={item.descripts + '^' + item.descriptsSPCode} title={item.descripts} value={String(item.id)}>{item.descripts}</Option>)
            })
            //开单类型
            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 className="configDeTemDom">
                    <Row gutter={60} className="majorCategoriesDom" style={{ marginRight: "0" }}>
                        <Col span={8} style={{ paddingRight: "0" }}>
                            <Card title="科室评估单配置列表" bordered={false} style={{ position:"relative" }} className="titleDom">
                            <Col span={5} style={{ position:"absolute",right:"-14px",top:"14px",padding:"0" }}>
                                <Button type="primary" onClick={this.addOutReg}>+评估单科室</Button>
                            </Col>
                                <DepAssFind OnChild={this.OnChild} handleQuery={this.handleQuery} onShowSizeChange={this.onShowSizeChange} sarchInit={this.sarchInit}  sendLoc={this.sendLoc}></DepAssFind>
                                <Table
                                    className="components-table-demo-nested"
                                    columns={leftDetailColumns}
                                    pagination={false}
                                    rowClassName={this.setRowClassName}
                                    onRow={this.onClickRow}
                                    rowKey={record => record.key}
                                    dataSource={this.state.leftData}
                                />
                                 <CommonPagination size={this.state.size} 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={16} style={{ paddingLeft: "6px", paddingRight: "0" }}>
                               <DepAssDetailed onDetail={this.onDetail} sendFile={this.sendFile}></DepAssDetailed>
                        </Col>
                    </Row>
                    <DepAssModal onRef={this.onRef} handleQuery={this.handleQuery}  getLast={this.getLast} sarchInit={this.sarchInit}></DepAssModal>
                </div>
            )
        }
    })
export default ConfigDepartmentalAssess
